<template>
  <div class="performance-ranking-container">
    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" :inline="true" label-width="80px">
        <el-form-item label="统计周期">
          <el-select v-model="filterForm.period" placeholder="请选择统计周期">
            <el-option label="本月" value="month" />
            <el-option label="本季度" value="quarter" />
            <el-option label="本年度" value="year" />
            <el-option label="自定义" value="custom" />
          </el-select>
        </el-form-item>
        
        <el-form-item v-if="filterForm.period === 'custom'" label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item label="分公司">
          <el-select v-model="filterForm.companyId" placeholder="请选择分公司" clearable>
            <el-option label="全部" value="" />
            <el-option
              v-for="company in companyList"
              :key="company.id"
              :label="company.name"
              :value="company.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="排行类型">
          <el-radio-group v-model="filterForm.rankType">
            <el-radio-button label="amount">成交金额</el-radio-button>
            <el-radio-button label="count">成交笔数</el-radio-button>
            <el-radio-button label="commission">佣金收入</el-radio-button>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleFilter" :loading="loading">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 排行榜头部 -->
    <el-row :gutter="20" class="ranking-header">
      <el-col :span="8">
        <el-card class="champion-card" shadow="never">
          <div class="champion-content" v-if="topThree[0]">
            <div class="champion-medal">
              <el-icon class="gold-medal"><Trophy /></el-icon>
              <span class="rank-number">1</span>
            </div>
            <div class="champion-info">
              <div class="champion-avatar">
                <el-avatar :size="60" :src="topThree[0].avatar">
                  {{ topThree[0].salesmanName?.charAt(0) }}
                </el-avatar>
              </div>
              <div class="champion-details">
                <div class="champion-name">{{ topThree[0].salesmanName }}</div>
                <div class="champion-company">{{ topThree[0].companyName }}</div>
                <div class="champion-value">
                  {{ getRankValue(topThree[0]) }}
                  <span class="unit">{{ getRankUnit() }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="runner-up-card" shadow="never">
          <div class="runner-up-content" v-if="topThree[1]">
            <div class="runner-up-medal">
              <el-icon class="silver-medal"><Trophy /></el-icon>
              <span class="rank-number">2</span>
            </div>
            <div class="runner-up-info">
              <div class="runner-up-avatar">
                <el-avatar :size="50" :src="topThree[1].avatar">
                  {{ topThree[1].salesmanName?.charAt(0) }}
                </el-avatar>
              </div>
              <div class="runner-up-details">
                <div class="runner-up-name">{{ topThree[1].salesmanName }}</div>
                <div class="runner-up-company">{{ topThree[1].companyName }}</div>
                <div class="runner-up-value">
                  {{ getRankValue(topThree[1]) }}
                  <span class="unit">{{ getRankUnit() }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="third-place-card" shadow="never">
          <div class="third-place-content" v-if="topThree[2]">
            <div class="third-place-medal">
              <el-icon class="bronze-medal"><Trophy /></el-icon>
              <span class="rank-number">3</span>
            </div>
            <div class="third-place-info">
              <div class="third-place-avatar">
                <el-avatar :size="50" :src="topThree[2].avatar">
                  {{ topThree[2].salesmanName?.charAt(0) }}
                </el-avatar>
              </div>
              <div class="third-place-details">
                <div class="third-place-name">{{ topThree[2].salesmanName }}</div>
                <div class="third-place-company">{{ topThree[2].companyName }}</div>
                <div class="third-place-value">
                  {{ getRankValue(topThree[2]) }}
                  <span class="unit">{{ getRankUnit() }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表分析 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <span>业绩趋势图</span>
          </template>
          <div ref="trendChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <span>分公司业绩对比</span>
          </template>
          <div ref="companyChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细排行榜 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>详细排行榜</span>
          <div class="header-actions">
            <el-button type="success" size="small" @click="handleExport">
              <el-icon><Download /></el-icon>
              导出排行榜
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        style="width: 100%"
        :row-class-name="getRowClassName"
      >
        <el-table-column label="排名" width="80" align="center">
          <template #default="{ $index }">
            <div class="rank-cell">
              <el-icon v-if="$index < 3" class="rank-icon" :class="getRankIconClass($index)">
                <Trophy />
              </el-icon>
              <span v-else class="rank-number">{{ $index + 1 }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="业务员" width="150">
          <template #default="{ row }">
            <div class="salesman-cell">
              <el-avatar :size="32" :src="row.avatar">
                {{ row.salesmanName?.charAt(0) }}
              </el-avatar>
              <span class="salesman-name">{{ row.salesmanName }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="companyName" label="分公司" width="120" />
        <el-table-column prop="amount" label="成交金额（万元）" width="140" align="right">
          <template #default="{ row }">
            <span class="amount-text">{{ formatNumber(row.amount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="dealCount" label="成交笔数" width="100" align="center" />
        <el-table-column prop="commission" label="佣金（万元）" width="120" align="right">
          <template #default="{ row }">
            <span class="commission-text">{{ formatNumber(row.commission) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="avgAmount" label="平均成交金额" width="140" align="right">
          <template #default="{ row }">
            {{ formatNumber(row.avgAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="customerCount" label="客户数量" width="100" align="center" />
        <el-table-column prop="conversionRate" label="转化率" width="100" align="center">
          <template #default="{ row }">
            <span :class="getConversionRateClass(row.conversionRate)">
              {{ (row.conversionRate * 100).toFixed(1) }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="growthRate" label="增长率" width="100" align="center">
          <template #default="{ row }">
            <span :class="getGrowthRateClass(row.growthRate)">
              <el-icon v-if="row.growthRate > 0"><ArrowUp /></el-icon>
              <el-icon v-else-if="row.growthRate < 0"><ArrowDown /></el-icon>
              {{ Math.abs(row.growthRate * 100).toFixed(1) }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleViewDetail(row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Download, Trophy, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 响应式数据
const loading = ref(false)
const trendChartRef = ref<HTMLDivElement>()
const companyChartRef = ref<HTMLDivElement>()

// 筛选表单
const filterForm = reactive({
  period: 'month',
  dateRange: [],
  companyId: '',
  rankType: 'amount'
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 表格数据
const tableData = ref([])

// 下拉选项
const companyList = ref([])

// 图表实例
let trendChart: echarts.ECharts | null = null
let companyChart: echarts.ECharts | null = null

// 计算属性
const topThree = computed(() => {
  return tableData.value.slice(0, 3)
})

// 方法
const handleFilter = () => {
  pagination.page = 1
  getTableData()
  updateCharts()
}

const handleReset = () => {
  Object.assign(filterForm, {
    period: 'month',
    dateRange: [],
    companyId: '',
    rankType: 'amount'
  })
  handleFilter()
}

const handleExport = () => {
  ElMessage.success('导出功能开发中')
}

const handleViewDetail = (row: any) => {
  ElMessage.info(`查看 ${row.salesmanName} 的详细业绩`)
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  getTableData()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  getTableData()
}

const getTableData = async () => {
  loading.value = true
  try {
    // TODO: 调用API获取数据
    setTimeout(() => {
      tableData.value = [
        {
          salesmanName: '张三',
          companyName: '北京分公司',
          amount: 1250.6,
          dealCount: 45,
          commission: 37.5,
          avgAmount: 27.8,
          customerCount: 120,
          conversionRate: 0.375,
          growthRate: 0.15,
          avatar: ''
        },
        {
          salesmanName: '李四',
          companyName: '上海分公司',
          amount: 980.3,
          dealCount: 38,
          commission: 29.4,
          avgAmount: 25.8,
          customerCount: 95,
          conversionRate: 0.4,
          growthRate: 0.08,
          avatar: ''
        },
        {
          salesmanName: '王五',
          companyName: '广州分公司',
          amount: 850.7,
          dealCount: 32,
          commission: 25.5,
          avgAmount: 26.6,
          customerCount: 88,
          conversionRate: 0.364,
          growthRate: -0.05,
          avatar: ''
        }
      ]
      pagination.total = 150
      loading.value = false
    }, 1000)
  } catch (error) {
    loading.value = false
    ElMessage.error('获取数据失败')
  }
}

const initCharts = () => {
  nextTick(() => {
    if (trendChartRef.value) {
      trendChart = echarts.init(trendChartRef.value)
    }
    if (companyChartRef.value) {
      companyChart = echarts.init(companyChartRef.value)
    }
    updateCharts()
  })
}

const updateCharts = () => {
  updateTrendChart()
  updateCompanyChart()
}

const updateTrendChart = () => {
  if (!trendChart) return
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['张三', '李四', '王五']
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value',
      name: '成交金额（万元）'
    },
    series: [
      {
        name: '张三',
        type: 'line',
        data: [180, 200, 220, 250, 280, 320],
        smooth: true
      },
      {
        name: '李四',
        type: 'line',
        data: [150, 170, 190, 210, 230, 250],
        smooth: true
      },
      {
        name: '王五',
        type: 'line',
        data: [120, 140, 160, 180, 200, 220],
        smooth: true
      }
    ]
  }
  trendChart.setOption(option)
}

const updateCompanyChart = () => {
  if (!companyChart) return
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: ['北京分公司', '上海分公司', '广州分公司', '深圳分公司', '杭州分公司']
    },
    yAxis: {
      type: 'value',
      name: '成交金额（万元）'
    },
    series: [
      {
        name: '成交金额',
        type: 'bar',
        data: [3250, 2890, 2150, 1980, 1650],
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        }
      }
    ]
  }
  companyChart.setOption(option)
}

// 工具方法
const formatNumber = (num: number) => {
  return num?.toFixed(2) || '0.00'
}

const getRankValue = (item: any) => {
  switch (filterForm.rankType) {
    case 'amount':
      return formatNumber(item.amount)
    case 'count':
      return item.dealCount
    case 'commission':
      return formatNumber(item.commission)
    default:
      return formatNumber(item.amount)
  }
}

const getRankUnit = () => {
  switch (filterForm.rankType) {
    case 'amount':
      return '万元'
    case 'count':
      return '笔'
    case 'commission':
      return '万元'
    default:
      return '万元'
  }
}

const getRowClassName = ({ rowIndex }: { rowIndex: number }) => {
  if (rowIndex === 0) return 'first-place-row'
  if (rowIndex === 1) return 'second-place-row'
  if (rowIndex === 2) return 'third-place-row'
  return ''
}

const getRankIconClass = (index: number) => {
  const classes = ['gold-medal', 'silver-medal', 'bronze-medal']
  return classes[index] || ''
}

const getConversionRateClass = (rate: number) => {
  if (rate >= 0.4) return 'high-rate'
  if (rate >= 0.3) return 'medium-rate'
  return 'low-rate'
}

const getGrowthRateClass = (rate: number) => {
  if (rate > 0) return 'positive-growth'
  if (rate < 0) return 'negative-growth'
  return 'zero-growth'
}

// 初始化数据
const initData = () => {
  companyList.value = [
    { id: '1', name: '北京分公司' },
    { id: '2', name: '上海分公司' },
    { id: '3', name: '广州分公司' },
    { id: '4', name: '深圳分公司' },
    { id: '5', name: '杭州分公司' }
  ]
  
  getTableData()
  initCharts()
}

onMounted(() => {
  initData()
})
</script>

<style lang="scss" scoped>
.performance-ranking-container {
  padding: 20px;
  
  .filter-card {
    margin-bottom: 20px;
  }
  
  .ranking-header {
    margin-bottom: 20px;
    
    .champion-card {
      border: 2px solid #ffd700;
      
      .champion-content {
        text-align: center;
        
        .champion-medal {
          position: relative;
          margin-bottom: 15px;
          
          .gold-medal {
            font-size: 48px;
            color: #ffd700;
          }
          
          .rank-number {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 18px;
            font-weight: bold;
            color: white;
          }
        }
        
        .champion-info {
          .champion-avatar {
            margin-bottom: 10px;
          }
          
          .champion-name {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 5px;
          }
          
          .champion-company {
            font-size: 14px;
            color: #666;
            margin-bottom: 10px;
          }
          
          .champion-value {
            font-size: 24px;
            font-weight: bold;
            color: #ffd700;
            
            .unit {
              font-size: 14px;
              margin-left: 5px;
            }
          }
        }
      }
    }
    
    .runner-up-card {
      border: 2px solid #c0c0c0;
      
      .runner-up-content {
        text-align: center;
        
        .runner-up-medal {
          position: relative;
          margin-bottom: 15px;
          
          .silver-medal {
            font-size: 40px;
            color: #c0c0c0;
          }
          
          .rank-number {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 16px;
            font-weight: bold;
            color: white;
          }
        }
        
        .runner-up-info {
          .runner-up-name {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 5px;
          }
          
          .runner-up-company {
            font-size: 12px;
            color: #666;
            margin-bottom: 10px;
          }
          
          .runner-up-value {
            font-size: 20px;
            font-weight: bold;
            color: #c0c0c0;
            
            .unit {
              font-size: 12px;
              margin-left: 5px;
            }
          }
        }
      }
    }
    
    .third-place-card {
      border: 2px solid #cd7f32;
      
      .third-place-content {
        text-align: center;
        
        .third-place-medal {
          position: relative;
          margin-bottom: 15px;
          
          .bronze-medal {
            font-size: 40px;
            color: #cd7f32;
          }
          
          .rank-number {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 16px;
            font-weight: bold;
            color: white;
          }
        }
        
        .third-place-info {
          .third-place-name {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 5px;
          }
          
          .third-place-company {
            font-size: 12px;
            color: #666;
            margin-bottom: 10px;
          }
          
          .third-place-value {
            font-size: 20px;
            font-weight: bold;
            color: #cd7f32;
            
            .unit {
              font-size: 12px;
              margin-left: 5px;
            }
          }
        }
      }
    }
  }
  
  .chart-row {
    margin-bottom: 20px;
    
    .chart-card {
      .chart-container {
        height: 300px;
      }
    }
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .rank-cell {
      display: flex;
      align-items: center;
      justify-content: center;
      
      .rank-icon {
        font-size: 24px;
        
        &.gold-medal {
          color: #ffd700;
        }
        
        &.silver-medal {
          color: #c0c0c0;
        }
        
        &.bronze-medal {
          color: #cd7f32;
        }
      }
      
      .rank-number {
        font-size: 16px;
        font-weight: bold;
      }
    }
    
    .salesman-cell {
      display: flex;
      align-items: center;
      
      .salesman-name {
        margin-left: 10px;
      }
    }
    
    .amount-text {
      color: #67c23a;
      font-weight: bold;
    }
    
    .commission-text {
      color: #e6a23c;
      font-weight: bold;
    }
    
    .high-rate {
      color: #67c23a;
      font-weight: bold;
    }
    
    .medium-rate {
      color: #e6a23c;
      font-weight: bold;
    }
    
    .low-rate {
      color: #f56c6c;
      font-weight: bold;
    }
    
    .positive-growth {
      color: #67c23a;
      font-weight: bold;
    }
    
    .negative-growth {
      color: #f56c6c;
      font-weight: bold;
    }
    
    .zero-growth {
      color: #909399;
    }
    
    .pagination-container {
      margin-top: 20px;
      text-align: right;
    }
  }
}

// 表格行样式
:deep(.first-place-row) {
  background-color: rgba(255, 215, 0, 0.1) !important;
}

:deep(.second-place-row) {
  background-color: rgba(192, 192, 192, 0.1) !important;
}

:deep(.third-place-row) {
  background-color: rgba(205, 127, 50, 0.1) !important;
}
</style>
